<script setup lang="ts">
import { useNurseUser, use_hospital_dept_bed, useNurseInformation, useNurseSwiper } from '@/service';
import { ref, computed, reactive, onBeforeUnmount, onMounted } from 'vue';
import { useAuthStore, useAppStore } from '@/store';
import { useRouterPush } from '@/composables';
import { storeToRefs } from 'pinia';
import Taro, { hideLoading, showLoading, showToast, usePullDownRefresh, stopPullDownRefresh } from '@tarojs/taro';
import { useGetAuthInfo, useGlobal, useImage } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useDayjs, useEmitter } from '@/hooks/common';
import HealthCard from './healthCard.vue';
import Tabs from './new-tabs.vue';
import Info from './info.vue';
import Movie from './movie.vue';
import Countdown from './countdown.vue';
import Thumb from './thumb.vue';
import good from './good.vue';
import { calculateDistance, localStg } from '@/utils';
// import { useNurseUser, use_hospital_dept_bed } from '@/service';
const emitter = useEmitter();

const { $dayjs } = useDayjs();

const { toHelp, toInformation, toNearShop } = useRouterPush();

// const { company } = storeToRefs(useNurseStore())
const { getHospitalListByArea, getConfig } = use_hospital_dept_bed();

const providerClass = computed(() => ' flex-col-center mt-4 w-360px  shadow  m_card  ');

const date = computed(() => (createTime: string) => {
  if (createTime) {
    const now = $dayjs();
    const date = $dayjs(createTime).from(now);
    return date;
  }
  return '';
});

const tabsRef = ref();
const myLocation = {latitude: 0, longitude: 0};
onMounted(() => {
  Taro.getLocation({
        type: 'wgs84',
        needFullAccuracy: true,
        success(res) {
          myLocation.latitude = res.latitude;
          myLocation.longitude = res.longitude;
          getData();
        }
    });
});

const { editDefaultHospital, getVisibleByHospital } = useNurseUser();

const { list } = useNurseInformation();

const { list: swiper_list } = useNurseSwiper();

const { nurseUser } = storeToRefs(useAuthStore());
const appStore = useAppStore();
const { setConfigVisible } = appStore;
const { configVisible } = storeToRefs(appStore);

console.log('nurseUser -----', nurseUser.value);

const { getHospitalList } = use_hospital_dept_bed();

useGlobal();

const swiperList = ref();

const informationList = ref();
const hospitalList = ref([])

const logoPic = computed(()=>{
  const id = nurseUser.value.defaultHospital;
  // console.error('id ====', id, hospitalList.value);
  let pic = ""
  hospitalList.value.forEach(item => {
    if(item.id === id) {
      pic = useImage(item.logo);
    }
  })
  // console.error('logoPic ====', pic);
  return pic
})

usePullDownRefresh(() => {
  getData();
  stopPullDownRefresh();
});

getData();

async function getData() {
  showLoading({ title: '正在请求...' });

  const reulst = await list();

  if (!reulst.error && reulst.success) informationList.value = reulst.success;
  // console.error("informationList.value", informationList.value)
  const { error, success } = await swiper_list();

  if (!error && success.records) swiperList.value = success.records;

  if (tabsRef.value) await tabsRef.value.getData();

  const { error: err, success:suc } = await getHospitalListByArea("南宁市");
  if (!err && suc) {
    console.log('success getHospitalListByArea', suc);
    hospitalList.value = suc
    console.log('success nurse 0000', nurseUser.value);
    changeDistance(suc)
  }

  // if (Object.keys(configVisible.value).length === 0) {
    const newConfig: Record<string, boolean> = {};
    const res = await getVisibleByHospital(nurseUser.value.defaultHospital as string);
    console.log("res 777", res);
    const str = res?.success?.records?.[0]?.mods;
    if (str) {
        str.split(',').forEach((item: any) => {
            newConfig[item] = true;
        });
    }
    setConfigVisible(newConfig);
    console.log('mods 888 from store', newConfig);
    console.log('configVisible 999 from store', configVisible.value);
  // }

  hideLoading();
}
const distance = ref<number | string>(0)

function changeDistance(list: any) {
  // nurseUser.distance = distance;
  list.forEach((item: any) => {
    if(item.name === nurseUser.value.defaultHospitalName) {
      // changeDistance(item.children);
      distance.value = calculateDistance(myLocation.latitude, myLocation.longitude, item.latitude, item.longitude, 2)
      nurseUser.value.defaultHospitalLatitude = item.latitude;
      nurseUser.value.defaultHospitalLongitude = item.longitude;
      // localStg.set('defaultHospital', JSON.stringify(item));
      Taro.setStorageSync('defaultHospital', JSON.stringify(item));
    }
  })
}

const hospitalModule = reactive({
  show: false,
  showHospital: () => {
    hospitalModule.show = !hospitalModule.show;
  },
  save: async ({ defaultHospital, defaultHospitalName }: any) => {
    showLoading({ title: '正在保存...' });
    const defaultaddr = nurseUser.value.nurseUserAddrList;
    if (defaultaddr && defaultaddr.length > 0) {
      defaultaddr[0] = {
        ...defaultaddr[0],
        hospital: defaultHospital,
        hospitalName: defaultHospitalName,
        dept: '',
        deptName: '',
        bed: '',
        bedName: ''
      };
    }
    const { error } = await editDefaultHospital({ userId: nurseUser.value.id, defaultHospital, defaultHospitalName });
    hideLoading();
    if (!error) {
      showToast({
        title: '保存成功',
        icon: 'success',
        duration: SUCCESS_MSG_DURATION
      });
      useGetAuthInfo();
    }
  },
  onChange: (items: any) => {
    if (items.length == 0) return;
    const item = items[items.length - 1];
    hospitalModule.show = false;
    hospitalModule.save({ defaultHospital: item.key, defaultHospitalName: item.title });
  },
  lazyLoad: async (pid: string) => {
    const { error, success } = await getHospitalList(pid);
    if (!error && success?.length > 0) {
      const list = success?.map((item: any) => {
        return {
          value: item,
          text: item.title
        };
      });
      return list;
    }
    return [];
  }
});

const text = ref('京东风格的移动端组件库，使用 Vue 语言来编写可以在 H5，小程序平台上的应用')

emitter.$on('select_hospital', () => {
  hospitalModule.show = true;
});

onBeforeUnmount(() => {
  emitter.$off('select_hospital');
});

// 切换医疗机构
function toNearShopNew() {
  Taro.navigateTo({
    url: '/package/nearshop/index',
    events: {
      switchNearShop(data: any) {
        getData(); // 切换城市后刷新机构
        stopPullDownRefresh();
      }
    }
  });
}

</script>

<template>
  <view class="w-375px text-primary flex-col-center mt-[var(--status-bar-height)] mt-30px">
    <view class="h-40px w-375px">
      <image class="w-full h-full" :src="logoPic" mode="aspectFit" />
    </view>

    <view class="h-60px w-375px">
      <view class="w-full h-full px-18rpx flex">
        <view class="h-full">
          <view class="flex px-18rpx h-full">
            <view class="flex-center text-#334155">
              <view class="flex items-center flex-col translate-y-[8rpx]">
                <view class="i-local-location w-12px h-12px" />
                <text class="text-[12rpx]">{{distance}}km</text>
              </view>
              <view class="text-[20rpx] max-w-[240rpx] truncate">{{ nurseUser.defaultHospitalName }}</view>
            </view>
            <view class="flex-center text-#334155 text-[16rpx]" @click="toNearShopNew()">
              <!-- <view class="i-local-switch w-18px h-18px" /> -->
              (切换机构)
            </view>
          </view>
        </view>
        <view class="flex-1 flex items-center px-1">
          <input type="text" class="flex-1 text-[16rpx] myx" placeholder="搜索" placeholder-class="text-gray-400" />
          <view class="i-local-search w-24px h-24px text-gray-400 mx-2" />
        </view>
      </view>
    </view>

    <!-- 搜索 -->
    <!-- <view class="w-375px px-18rpx py-2">
      <view class="flex items-center bg-white rounded-full h-36px">
        <view class="flex items-center text-gray-600 px-4">
          <view class="i-local-location w-18px h-18px mr-1 text-green-500" />
          <text class="text-sm">南宁市 (20km)</text>
          <view class="i-local-arrow-down w-18px h-18px ml-1" />
        </view>
        <view class="flex-1 flex items-center px-2">
          <input type="text" class="flex-1 text-sm iptx" placeholder="搜索" placeholder-class="text-gray-400" />
          <view class="i-local-search w-24px h-24px text-gray-400 mx-2" />
        </view>
      </view>
    </view> -->

    <nut-noticebar class="w-full" :text="text" v-if="configVisible.broadcast"/>
    

    <view v-if="configVisible.swiper"
      class="w-375px flex-col-center justify-between items-center bg-gradient-to-bl from-#f39c12/60 via-#2ecc71:80 to-#9b59b6_70">

      <view class="w-375px">
        <!-- class="b-rounded-t-3" -->
        <nut-swiper :init-page="0" :auto-play="3000" pagination-visible pagination-color="#059669"
          pagination-unselected-color="#808080">
          <nut-swiper-item v-for="(item, index) in swiperList" :key="index" class="swiper_item"
            @click="toInformation(item.toInformation)">
            <image :src="useImage(item.pic)" alt="" class="swiper_img" mode="aspectFill	" draggable="false" />
          </nut-swiper-item>
        </nut-swiper>
      </view>
    </view>

   
      <view class="w-375px py-18rpx" v-show="configVisible.card">
        <view class="h-full flex-col-center px-10rpx">
          <HealthCard />
        </view>
      </view>

    <Info v-if="configVisible.info" />
    <Movie v-if="configVisible.video" />
    <Countdown v-if="configVisible.live" title="医疗专家直播" :target-timestamp="Date.now() + 1000 * 60 * 60 * 24 * 7" />
    <Countdown v-if="configVisible.team" title="护理服务团购" :target-timestamp="Date.now() + 1000 * 60 * 60 * 14 * 1" />
    <Thumb v-if="configVisible.thumb"></Thumb>


   
    <view class="w-375px">
      <view class="flex-col-center px-18rpx">
        <Tabs ref="tabsRef" :hospital="nurseUser?.defaultHospital || ''" />
      </view>
    </view>
    <!-- <view class="w-360px mb-1">
      <view class="font-bold ml-4 m-t-1 m-b-2 text-#334155 text-20px">动态资讯</view>
      <view v-for="item in informationList"
        :class="[item.isTop === '1' ? `${providerClass}   h-240px ` : `${providerClass} h-140px`]"
        @click="toInformation(item.id)">
        <view v-if="item.isTop === '1'" class="w-full h-full flex-col-center">
          <view class="mb-1 w-full h-auto flex-col-center font-bold text-lg">
            {{ item.title }}
          </view>
          <view class="w-350px h-full">
            <image :src="useImage(item.pic)" alt="" class="_img" draggable="false" />
          </view>
          <view class="mb-1 mr-1 w-full h-auto text-blueGray flex justify-end">
            <nut-ellipsis direction="end" :content="item.title"></nut-ellipsis>
          </view>
        </view>
        <view v-if="item.isTop !== '1'" class="w-full h-full flex-col-center">
          <view class="w-350px h-full flex">
            <view class="w-100px h-100px">
              <image :src="useImage(item.pic)" alt="" draggable="false" />
            </view>
            <view class="w-250px ml-1 h-full">
              <view class="w-full h-auto flex font-bold text-lg justify-start">
                <nut-ellipsis rows="2" direction="end" :content="item.title"></nut-ellipsis>
              </view>
              <view class="w-full h-auto text-blueGray flex justify-start">
                <nut-ellipsis rows="2" direction="end" :content="item.title"></nut-ellipsis>
              </view>
            </view>
          </view>
        </view>

        <view class="text-14px text mb-1 mr-1 w-full h-auto flex justify-end">
          <view class="p-2px">
            {{ date(item.createTime) }}
          </view>
        </view>
      </view>
    </view> -->
  </view>
  <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
    :title="nurseUser.defaultHospitalName" @change="hospitalModule.onChange" />
  <view class="bg-primary w-48px h-48px b-rounded-1/2 pos-fixed pos-bottom-80px pos-right-20px flex-center"
    @click="toHelp">
    <view class="i-local-phone-sharp w-24px h-24px text-white" />
  </view>
</template>
<style lang="scss">
.m_card {
  backdrop-filter: blur(10px) brightness(90%);
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
}

.swiper_item {
  height: 120px;
}

.swiper_img {
  height: 100%;
  width: 100%;
}

._img {
  height: 100%;
  width: 100%;
  border-radius: 24rpx;
}

.iptx {
  border: solid 1px #999;
  border-radius: 30rpx;
  padding: 7rpx 20rpx;
}
.myx{
  font-size: 20rpx !important;
  border: solid 1px #ddd;
  padding: 4rpx 30rpx;
  border-radius: 30rpx;
}
</style>
